package com.camelot.ccr.global.util.comparator;

import java.beans.PropertyDescriptor;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.Comparator;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * 定义公共的排序对象，实现排序的对象需要继承此类，重新相关的函数
 * 默认将某些为null值的属性，按对应的""空字符串来比较
 * @author chendd
 */
public class CommonComparator<T> implements Comparator<T> {

	/**
	 * 中文排序对象
	 */
	RuleBasedCollator collator = (RuleBasedCollator)Collator.getInstance(Locale.CHINA);
	
	/**
	 * @return 0正序，1倒序
	 */
	private int sort = 0;
	
	/**
	 * 定义需要排序的属性集合，按先后顺序来
	 */
	public String[] sortAttrs;
	
	public int compare(T t1, T t2,String attrs[] , int index){
		int result = -1;
		boolean flag = true;
		try {
			if(index >= attrs.length){
				flag = false;
			}
			if (flag) {
				String attrName = attrs[index];
				PropertyDescriptor prop1 = new PropertyDescriptor(attrName, t1.getClass());
				PropertyDescriptor prop2 = new PropertyDescriptor(attrName, t2.getClass());
				Object t1Value = prop1.getReadMethod().invoke(t1, new Object[] {});
				Object t2Value = prop2.getReadMethod().invoke(t2, new Object[] {});
				int i = 0;
				if(t1Value == null){
					t1Value = "";
				}
				if(t2Value == null){
					t2Value = "";
				}
				boolean isIndexChinese = Pattern.compile("[\\u4e00-\\u9fa5]+").matcher(t1Value.toString()).find();
				if(isIndexChinese){
					if(this.sort == 0){
						i = collator.compare(t1Value, t2Value);
					}else if(this.sort == 1){
						i = collator.compare(t2Value, t1Value);
					}else{
						throw new Exception("getSort函数的调用参数不合法");
					}
				}else{
					if(this.sort == 0){
						i = t1Value.toString().compareTo(t2Value.toString());
					}else if(this.sort == 1){
						i = t2Value.toString().compareTo(t1Value.toString());
					}else{
						throw new Exception("getSort函数的调用参数不合法");
					}
				}
				if (i == 0) {
					// 继续比较下一个属性
					i = compare(t1, t2, attrs, index + 1);
				}
				result = i;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public int compare(T obj1, T obj2) {
		int i = 0;
		try {
			String attrs[] = this.sortAttrs;
			i = this.compare(obj1, obj2, attrs, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}


	public void setSort(int sort) {
		this.sort = sort;
	}

	public void setSortAttrs(String[] sortAttrs) {
		this.sortAttrs = sortAttrs;
	}
	
}
